package cn.itsource.pethome.system.menu.controller;

import cn.itsource.pethome.system.menu.service.IMenuService;
import cn.itsource.pethome.system.menu.domain.Menu;
import cn.itsource.pethome.system.menu.query.MenuQuery;
import cn.itsource.pethome.utils.AjaxResult;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import javax.annotation.Resource;

@RestController
@RequestMapping("/menu")
@Api(value = "菜单API",description="菜单相关的CRUD功能")
public class MenuController {
    @Resource
    public IMenuService menuService;

    @GetMapping("/tree")
    public List<Menu> tree(){
        return menuService.getMenuTree();
    }

    @GetMapping("/first")
    public AjaxResult first() {
        try {
            List<Menu> byQuery = menuService.findFirst();
            return AjaxResult.success().setData(byQuery);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }



    /**
     * 保存和修改公用的
     * @param menu  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Menu menu){
        try {
            if( menu.getId()!=null){
                menuService.update(menu);
                return AjaxResult.success().setMsg("修改成功!");
            }
            else{
                menuService.add(menu);
                return AjaxResult.success().setMsg("添加成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg(e.getMessage());
        }
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            menuService.delete(id);
            return AjaxResult.success().setMsg("删除成功");
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.error().setMsg(e.getMessage());
        }
    }
	
    //获取用户
    @GetMapping("/{id}")
    public Menu get(@PathVariable("id")Long id)
    {
        return menuService.findOne(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<Menu> list(){
        return menuService.findAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public AjaxResult json(@RequestBody MenuQuery query)
    {
        try {
            List<Menu> query1 = menuService.findQuery(query);
            Long aLong = menuService.countPage(query);
            return AjaxResult.success().setData(query1).setTotal(aLong);
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.error();
    }
}
